package xyz.ibenben.zhongdian.system.service.sys.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import org.springframework.util.StringUtils;

import tk.mybatis.mapper.entity.Example;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.dao.sys.SysRoleResourcesDao;
import xyz.ibenben.zhongdian.system.entity.sys.SysRoleResources;
import xyz.ibenben.zhongdian.system.mapper.sys.SysRoleResourcesMapper;
import xyz.ibenben.zhongdian.system.service.sys.SysRoleResourcesService;

/**
 * 系统角色资源服务实现类
 * 系统级角色管理所使用的，是权限系统中的一部分
 * 提供了一些基本的服务，如添加角色资源、通过角色主键删除记录等方法。
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service
public class SysRoleResourcesServiceImpl implements SysRoleResourcesService {
	private final SysRoleResourcesMapper sysRoleResourcesMapper;
	private final SysRoleResourcesDao sysRoleResourcesDao;

	@Autowired
	public SysRoleResourcesServiceImpl(SysRoleResourcesMapper sysRoleResourcesMapper, SysRoleResourcesDao sysRoleResourcesDao) {
		this.sysRoleResourcesMapper = sysRoleResourcesMapper;
		this.sysRoleResourcesDao = sysRoleResourcesDao;
	}
	//@Resource
	//private ShiroService shiroService

	/**
	 * addRoleResources角色资源关系记录
	 * @param roleResources 参数
	 */
	@Override
	@Transactional(propagation= Propagation.REQUIRED, readOnly=false, rollbackFor={Exception.class})
	@CacheEvict(cacheNames="sysResources", allEntries=true)
	@SystemServiceLog(description = "addRoleResources角色资源关系记录")
	public void addRoleResources(SysRoleResources roleResources) {
		//更新权限
		//删除
		Example example = new Example(SysRoleResources.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("roleId",roleResources.getRoleId());
		sysRoleResourcesDao.deleteByExample(example);
		//添加
		if(!StringUtils.isEmpty(roleResources.getResourcesIds())){
			String[] resourcesArr = roleResources.getResourcesIds().split(Constants.COMMA);
			for(String resourcesId: resourcesArr){
				SysRoleResources r = new SysRoleResources();
				r.setRoleId(roleResources.getRoleId());
				r.setResourcesId(Long.parseLong(resourcesId));
				sysRoleResourcesMapper.insert(r);
			}
		}
		//List<Integer> userIds= userRoleMapper.findUserIdByRoleId(roleResources.getRoleid())
		//更新当前登录的用户的权限缓存
		//shiroService.clearUserAuthByUserId(userIds)
	}

	/**
	 * addRoleResources角色资源关系记录
	 * @param roleId 参数
	 * @return 返回值
	 */
	@Transactional
	@Override
	@SystemServiceLog(description = "addRoleResources角色资源关系记录")
	public int deleteByRoleId(Object roleId) {
		Example example = new Example(SysRoleResources.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("roleId", roleId);
		return sysRoleResourcesDao.deleteByExample(example);
	}

}
